import axios from 'axios';
import util from './util.js';
import APIException from "./exceptions/APIException.js";
import EX from "./exceptions/Exception.js";
import { generateCookie } from './cookie.js'


// 伪装headers
const FAKE_HEADERS = {
    Accept: "*/*",
    "Accept-Encoding": "gzip, deflate, br, zstd",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
    Origin: "https://chat.deepseek.com",
    Pragma: "no-cache",
    Priority: "u=1, i",
    Referer: "https://chat.deepseek.com/",
    "Sec-Ch-Ua":
      '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": '"Windows"',
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent":
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
    "X-App-Version": "20241129.1"
};

let ipAddress = '' // 当前IP地址
const EVENT_COMMIT_ID = '41e9c7b1';
export const sendEvents = async (refConvId, refreshToken) => {  // 接受聊天频道id 和 用户token
    try {
        const token =  refreshToken;
        const sessionId = `session_v0_${Math.random().toString(36).slice(2)}`;
        const timestamp = util.timestamp();
        const fakeDuration1 = Math.floor(Math.random() * 1000);
        const fakeDuration2 = Math.floor(Math.random() * 1000);
        const fakeDuration3 = Math.floor(Math.random() * 1000);
        const ipAddress = await getIPAddress();
        const response = await axios.post('https://chat.deepseek.com/api/v0/events', {
          "events": [
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp,
              "event_name": "__reportEvent",
              "event_message": "调用上报事件接口",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "method": "post",
                "url": "/api/v0/events",
                "path": "/api/v0/events"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 100 + Math.floor(Math.random() * 1000),
              "event_name": "__reportEventOk",
              "event_message": "调用上报事件接口成功",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "method": "post",
                "url": "/api/v0/events",
                "path": "/api/v0/events",
                "logId": util.uuid(),
                "metricDuration": Math.floor(Math.random() * 1000),
                "status": "200"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 200 + Math.floor(Math.random() * 1000),
              "event_name": "createSessionAndStartCompletion",
              "event_message": "开始创建对话",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "__referrer": "",
                "agentId": "chat",
                "thinkingEnabled": false
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 300 + Math.floor(Math.random() * 1000),
              "event_name": "__httpRequest",
              "event_message": "httpRequest POST /api/v0/chat_session/create",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "__referrer": "",
                "url": "/api/v0/chat_session/create",
                "path": "/api/v0/chat_session/create",
                "method": "POST"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 400 + Math.floor(Math.random() * 1000),
              "event_name": "__httpResponse",
              "event_message": `httpResponse POST /api/v0/chat_session/create, ${Math.floor(Math.random() * 1000)}ms, reason: none`,
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "url": "/api/v0/chat_session/create",
                "path": "/api/v0/chat_session/create",
                "method": "POST",
                "metricDuration": Math.floor(Math.random() * 1000),
                "status": "200",
                "logId": util.uuid()
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 500 + Math.floor(Math.random() * 1000),
              "event_name": "__log",
              "event_message": "使用 buffer 模式",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": ""
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 600 + Math.floor(Math.random() * 1000),
              "event_name": "chatCompletionApi",
              "event_message": "chatCompletionApi 被调用",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "scene": "completion",
                "chatSessionId": refConvId,
                "withFile": "false",
                "thinkingEnabled": "false"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 700 + Math.floor(Math.random() * 1000),
              "event_name": "__httpRequest",
              "event_message": "httpRequest POST /api/v0/chat/completion",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "url": "/api/v0/chat/completion",
                "path": "/api/v0/chat/completion",
                "method": "POST"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 800 + Math.floor(Math.random() * 1000),
              "event_name": "completionFirstChunkReceived",
              "event_message": "收到第一个 completion chunk（可以是空 chunk）",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "metricDuration": Math.floor(Math.random() * 1000),
                "logId": util.uuid()
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 900 + Math.floor(Math.random() * 1000),
              "event_name": "createSessionAndStartCompletion",
              "event_message": "创建会话并开始补全",
              "payload": {
                "__location": "https://chat.deepseek.com/",
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "agentId": "chat",
                "newSessionId": refConvId,
                "isCreateNewChat": "false",
                "thinkingEnabled": "false"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 1000 + Math.floor(Math.random() * 1000),
              "event_name": "routeChange",
              "event_message": `路由改变 => /a/chat/s/${refConvId}`,
              "payload": {
                "__location": `https://chat.deepseek.com/a/chat/s/${refConvId}`,
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "to": `/a/chat/s/${refConvId}`,
                "redirect": "false",
                "redirected": "false",
                "redirectReason": "",
                "redirectTo": "/",
                "hasToken": "true",
                "hasUserInfo": "true"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 1100 + Math.floor(Math.random() * 1000),
              "event_name": "__pageVisit",
              "event_message": `访问页面 [/a/chat/s/${refConvId}] [0]：${fakeDuration1}ms`,
              "payload": {
                "__location": `https://chat.deepseek.com/a/chat/s/${refConvId}`,
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "pathname": `/a/chat/s/${refConvId}`,
                "metricVisitIndex": 0,
                "metricDuration": fakeDuration1,
                "referrer": "none",
                "appTheme": "light"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 1200 + Math.floor(Math.random() * 1000),
              "event_name": "__tti",
              "event_message": `/a/chat/s/${refConvId} TTI 上报：${fakeDuration2}ms`,
              "payload": {
                "__location": `https://chat.deepseek.com/a/chat/s/${refConvId}`,
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "type": "warmStart",
                "referer": "",
                "metricDuration": fakeDuration2,
                "metricVisitIndex": 0,
                "metricDurationSinceMounted": 0,
                "hasError": "false"
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 1300 + Math.floor(Math.random() * 1000),
              "event_name": "__httpResponse",
              "event_message": `httpResponse POST /api/v0/chat/completion, ${fakeDuration3}ms, reason: none`,
              "payload": {
                "__location": `https://chat.deepseek.com/a/chat/s/${refConvId}`,
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "url": "/api/v0/chat/completion",
                "path": "/api/v0/chat/completion",
                "method": "POST",
                "metricDuration": fakeDuration3,
                "status": "200",
                "logId": util.uuid()
              },
              "level": "info"
            },
            {
              "session_id": sessionId,
              "client_timestamp_ms": timestamp + 1400 + Math.floor(Math.floor(Math.random() * 1000)),
              "event_name": "completionApiOk",
              "event_message": "完成响应，响应有正常的的 finish reason",
              "payload": {
                "__location": `https://chat.deepseek.com/a/chat/s/${refConvId}`,
                "__ip": ipAddress,
                "__region": "CN",
                "__pageVisibility": "true",
                "__nodeEnv": "production",
                "__deployEnv": "production",
                "__appVersion": FAKE_HEADERS["X-App-Version"],
                "__commitId": EVENT_COMMIT_ID,
                "__userAgent": FAKE_HEADERS["User-Agent"],
                "__referrer": "",
                "condition": "hasDone",
                "streamClosed": false,
                "scene": "completion",
                "chatSessionId": refConvId
              },
              "level": "info"
            }
          ]
        }, {
          headers: {
            Authorization: `Bearer ${token}`,
            ...FAKE_HEADERS,
            Referer: `https://chat.deepseek.com/a/chat/s/${refConvId}`,
            Cookie: await generateCookie()
          },
          validateStatus: () => true,
        });
        logger.info(`${refConvId} 访问事件上报成功`);
    } catch (err) {
        logger.error(err);
    } 
}

// 获取IP地址
async function getIPAddress() {
    if (ipAddress) return ipAddress;
    const result = await axios.get('https://chat.deepseek.com/', {
      headers: {
        ...FAKE_HEADERS,
        Cookie: await generateCookie()
      },
      timeout: 15000,
      validateStatus: () => true,
    });
    const ip = result.data.match(/<meta name="ip" content="([\d.]+)">/)?.[1];
    if (!ip) throw new APIException(EX.API_REQUEST_FAILED, '获取IP地址失败');
    logger.info(`当前IP地址: ${ip}`);
    ipAddress = ip;
    return ip;
}